package com.lemon.smartsafety.ui.activity.safe.data;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatRadioButton;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableRow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.CommonVoEx;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildTypeEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingGroupVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.fragment.safe.data.SafeDataCollectionBuildingTypeListFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Cooliean on 16/3/25.
 */
public class SafeDataCollectionBuildingPropActivity extends PhotoSelectBaseActivity {
    //private LoggerHelper loggerHelper = new LoggerHelper(SafeDataCollectionBuildingPropActivity.class);

    @Bind(R.id.metBuildTitle)
    MaterialEditText     metBuildTitle;
    @Bind(R.id.metPlaceType)
    MaterialEditText     metPlaceType;
    @Bind(R.id.rowPlaceType)
    TableRow             rowPlaceType;
    @Bind(R.id.metBuildingGroup)
    MaterialEditText     metBuildingGroup;
    @Bind(R.id.rowGroupSetting)
    TableRow             rowGroupSetting;
    @Bind(R.id.metRemark)
    MaterialEditText     metRemark;
    @Bind(R.id.radioAll)
    AppCompatRadioButton radioAll;
    @Bind(R.id.radioPart)
    AppCompatRadioButton radioPart;

    @Bind(R.id.metFloorUp)
    MaterialEditText metFloorUp;
    @Bind(R.id.metFloorDown)
    MaterialEditText metFloorDown;
    @Bind(R.id.iv_photo)
    ImageView        ivPhoto;
    @Bind(R.id.rowPhotoPick)
    TableRow         rowPhotoPick;
    @Bind(R.id.metEast)
    MaterialEditText metEast;
    @Bind(R.id.metSouth)
    MaterialEditText metSouth;
    @Bind(R.id.metWest)
    MaterialEditText metWest;
    @Bind(R.id.metNorth)
    MaterialEditText metNorth;
    @Bind(R.id.btn_submit)
    Button           btnSubmit;


    /**
     * 建筑分类
     */
    private CommonVoEx placeTypeVo      = null;
    private String     txtBuildingTitle = "";
    private String     txtFloor         = "";
    private String     txtUnder         = "";
    private String     txtEast          = "";
    private String     txtSouth         = "";
    private String     txtWest          = "";
    private String     txtNorth         = "";


    private PhotoInfo mPhotoInfo;

    private MaterialDialog.Builder mMaterialDialog;

    private boolean isEdit = false;
    private CompanyBuildingVo mCompanyBuildingVo;
    private CompanyInfo       mCompanyInfo;
    private SelectDataI       mBuildingGroup;

    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.build_prop_title);
    }


    /****************************************************************************************************************
     * 保护现场
     ****************************************************************************************************************/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        outState.putSerializable(BundleKey.COMPANY_INFO, mCompanyInfo);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILD_INFO);
            mCompanyInfo = (CompanyInfo) savedInstanceState.getSerializable(BundleKey.COMPANY_INFO);
        }
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
            mCompanyBuildingVo = (CompanyBuildingVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILD_INFO);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        ivPhoto.setTag("0");

        if (null == mCompanyInfo) {
            mHUDUtil.showErrorTip(R.string.params_error);
            AppManager.getAppManager().finishActivity(SafeDataCollectionBuildingPropActivity.this);
            return;
        }

        if (null != mCompanyBuildingVo) {
            isEdit = true;
            initEditView(mCompanyBuildingVo);
        }


    }

    private void initEditView(CompanyBuildingVo vo) {
        metBuildTitle.setText(StringUtils.nullValue(vo.getBuildingTitle()));
        metPlaceType.setText(StringUtils.nullValue(vo.getBuildType().getName()));
        placeTypeVo = vo.getBuildType();

        CompanyBuildingGroupVo group = new CompanyBuildingGroupVo();
        group.setSelected(true);
        group.setGroupId(StringUtils.nullValue(vo.getGroupIds()));
        group.setGroupName(StringUtils.nullValue(vo.getGroupName()));
        mBuildingGroup = group;
        metBuildingGroup.setText(StringUtils.nullValue(mBuildingGroup.getTitle()));
        metBuildingGroup.setTag(StringUtils.nullValue(mBuildingGroup.getValue()));


        metRemark.setText(StringUtils.nullValue(vo.getRemark()));
        if (StringUtils.nullValue(vo.getOccupy()).equals("0")) {
            radioAll.setChecked(false);
            radioPart.setChecked(true);
        } else {
            radioAll.setChecked(true);
            radioPart.setChecked(false);
        }
        metFloorUp.setText(StringUtils.nullValue(vo.getFloor()));
        metFloorDown.setText(StringUtils.nullValue(vo.getUnder()));
        metEast.setText(StringUtils.nullValue(vo.getEast()));
        metSouth.setText(StringUtils.nullValue(vo.getSouth()));
        metWest.setText(StringUtils.nullValue(vo.getWest()));
        metNorth.setText(StringUtils.nullValue(vo.getNorth()));

        String photoUrl = StringUtils.nullValue(vo.getImageUrl());
        if (photoUrl.length() != 0) {
            photoUrl = HttpUtils.formatFilesUrl(photoUrl);
            mPhotoInfo = new PhotoInfo();
            mPhotoInfo.setPhotoId(Integer.MAX_VALUE);
            mPhotoInfo.setPhotoPath(photoUrl);
            ivPhoto.setTag(photoUrl);

            GlideImageLoader.loadImage(this, photoUrl, ivPhoto);
        } else {
            ivPhoto.setTag("0");
        }


    }


    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        if (EventTag.BUILDING_GROUP_LIST.equals(event.getTag())) {
            mBuildingGroup = event.getData();
            metBuildingGroup.setText(StringUtils.nullValue(mBuildingGroup.getTitle()));
            metBuildingGroup.setTag(StringUtils.nullValue(mBuildingGroup.getValue()));
        }
    }


    @Subscribe
    public void onEventMainThread(BuildTypeEvent event) {
        if (SafeDataCollectionBuildingTypeListFragment.class.getName().equals(event.getTag())) {
            placeTypeVo = (CommonVoEx) event.getData();
            if (placeTypeVo != null) {
                metPlaceType.setText(StringUtils.nullValue(placeTypeVo.getName()));
            }
        }
    }

    @OnClick(R.id.rowPlaceType)
    public void rowPlaceTypeClick() {
        showBuildingTypeList();
    }

    @OnClick(R.id.metPlaceType)
    public void metPlaceTypeClick() {
        showBuildingTypeList();
    }

    private void showBuildingTypeList() {
        if (placeTypeVo != null) {
            Bundle bundle = new Bundle();
            bundle.putString(BundleKey.OLD_SELECT_VALUE, StringUtils.nullValue(placeTypeVo.getExTitle()));
            UIHelper.showSafeDataCollectionBuildingTypeList(this, bundle);
        } else {
            UIHelper.showSafeDataCollectionBuildingTypeList(this, null);
        }
    }

    @Override
    protected void callFinish() {
        mMaterialDialog = null;
        mCompanyBuildingVo = null;
        mCompanyInfo = null;
        IApplication._tempBuildPropActivity = null;
        AppManager.getAppManager().finishActivity(SafeDataCollectionBuildingPropActivity.class);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_building_prop;
    }


    @OnClick({R.id.iv_photo, R.id.rowPhotoPick})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_photo:
                if ("0".equals(ivPhoto.getTag()) || "".equals(ivPhoto.getTag())) {
                    showSelectPhoto();
                } else {
                    PhotoInfo photoInfo = new PhotoInfo();
                    photoInfo.setPhotoId(Integer.MAX_VALUE);
                    photoInfo.setPhotoPath(StringUtils.nullValue(ivPhoto.getTag().toString()));
                    UIHelper.showPhotoView(SafeDataCollectionBuildingPropActivity.this, photoInfo);
                }
                break;
            case R.id.rowPhotoPick:
                showSelectPhoto();
                break;
        }
    }

    @OnClick({R.id.metBuildingGroup, R.id.rowGroupSetting})
    public void buildGroupingSetting(View view) {
        Bundle bundle = new Bundle();
        if (mBuildingGroup != null) {
            bundle.putString(BundleKey.OLD_SELECT_VALUE, mBuildingGroup.getValue());
        }
        bundle.putString(BundleKey.COMPANY_CODE, StringUtils.nullValue(mCompanyInfo.getCompany_code()));
        UIHelper.showActivity(this, bundle, BuildingGroupListActivity.class);
    }

    /**
     * 显示选择照片的界面
     */
    public void showSelectPhoto() {
        showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_SINGLE);
    }


    @Override
    protected void onSinglePhotoSuccess(int requestCode, PhotoInfo photoInfo) {
        super.onSinglePhotoSuccess(requestCode, photoInfo);
        this.mPhotoInfo = photoInfo;
        ivPhoto.setTag(StringUtils.nullValue(photoInfo.getPhotoPath()));
        GlideImageLoader.loadImage(this, StringUtils.nullValue(photoInfo.getPhotoPath()), ivPhoto);
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        /**
         * 请填写建筑名称
         */
        txtBuildingTitle = StringUtils.nullValue(metBuildTitle.getText().toString().trim());
        if (TextUtils.isEmpty(txtBuildingTitle)) {
            metBuildTitle.setError(getString(R.string.build_prop_error_building_title));
            mHUDUtil.showErrorTip(getString(R.string.build_prop_error_building_title));
            return false;
        }


        /**
         * 请选择场所分类
         */
        if (placeTypeVo == null) {
            metBuildTitle.setError(getString(R.string.build_prop_error_building_type));
            mHUDUtil.showErrorTip(getString(R.string.build_prop_error_building_type));
            return false;
        }


        /**
         * 请填写地上层数
         */
        txtFloor = StringUtils.nullValue(metFloorUp.getText().toString().trim());
        txtFloor=txtFloor.replace("，",",");
        if (TextUtils.isEmpty(txtFloor)) {
            metFloorUp.setError(getString(R.string.build_prop_error_floor_up_empty));
            mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_up_empty));
            return false;
        }


        /**
         * 请填写地下层数
         */
        txtUnder = StringUtils.nullValue(metFloorDown.getText().toString().trim());
        if (TextUtils.isEmpty(txtUnder)) {
            txtUnder = "0";
            metFloorDown.setText("0");
        }


        boolean chkOccupy = radioAll.isChecked();

        if (chkOccupy) {
            if (!floorNumberCheck2(txtFloor)) {
                metFloorUp.setError(getString(R.string.build_prop_error_floor_up_format));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_up_format));
                return false;
            }
            if (!floorNumberCheck2(txtUnder)) {
                metFloorDown.setError(getString(R.string.build_prop_error_floor_down_format));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_down_format));
                return false;
            }
        } else {
            if (!floorNumberCheck(txtFloor)) {
                metFloorUp.setError(getString(R.string.build_prop_error_floor_format_tip));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_format_tip));
                return false;
            }
            if (!floorNumberCheck(txtUnder)) {
                metFloorDown.setError(getString(R.string.build_prop_error_floor_format_tip));
                mHUDUtil.showErrorTip(getString(R.string.build_prop_error_floor_format_tip));
                return false;
            }
        }


        txtEast = metEast.getText().toString().trim();
        txtSouth = metSouth.getText().toString().trim();
        txtWest = metWest.getText().toString().trim();
        txtNorth = metNorth.getText().toString().trim();


      /*  if(CommonUtil.strIsEmpty(txtEast)){
            metEast.setError("方位东,没有填写");
            mHUDUtil.showErrorTip("方位东,没有填写");
            return false;
        }

        if(CommonUtil.strIsEmpty(txtSouth)){
            metSouth.setError("方位南,没有填写");
            mHUDUtil.showErrorTip("方位南,没有填写");
            return false;
        }

        if(CommonUtil.strIsEmpty(txtWest)){
            metWest.setError("方位西,没有填写");
            mHUDUtil.showErrorTip("方位西,没有填写");
            return false;
        }

        if(CommonUtil.strIsEmpty(txtNorth)){
            metNorth.setError("方位北,没有填写");
            mHUDUtil.showErrorTip("方位北,没有填写");
            return false;
        }*/



        return true;

    }


    private boolean floorNumberCheck(String s) {
        //Pattern p1 = Pattern.compile("(^\\d+,?(-?\\d+,?)+(\\d+-)?\\d+$)|(^\\d+$)|(^\\d+(-{1})?\\d+$)");
        Pattern p1 = Pattern.compile("(^\\d+([,-]\\d+)*$)|(^\\d+([,-]\\d+)*$)");
        return p1.matcher(s).matches();
    }

    private boolean floorNumberCheck2(String s) {
        Pattern p1 = Pattern.compile("^\\d+$");
        return p1.matcher(s).matches();
    }


    @OnClick(R.id.btn_submit)
    protected void btnSubmitAction() {
        if (!validateForm()) {
            return;
        }


        mMaterialDialog = getConfirmDialog(getString(R.string.is_submit), new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doPostAction();
                }
            }
        });
        mMaterialDialog.show();

    }


    private void doPostAction() {
        final LemonRequestParams params = new LemonRequestParams("company_building", "building_id", "");
        params.put("_txtIdNumeric", "0");
        if (isEdit) {
            params.put("_txtIdValues", StringUtils.nullValue(mCompanyBuildingVo.getBuildingId().trim()));
            params.put("building_id", StringUtils.nullValue(mCompanyBuildingVo.getBuildingId().trim()));
        } else {
            params.put("_txtIdValues", "");
            params.put("building_id", "");
        }

        if (mBuildingGroup != null) {
            params.put("txtGroupIds", mBuildingGroup.getValue(), Field.TYPE_STRING);
        }
        params.put("txtBuildingTitle", txtBuildingTitle, Field.TYPE_STRING);
        params.put("selBuildingTypeCode", placeTypeVo.getExTitle(), Field.TYPE_STRING);
        params.put("txtRemark", metRemark.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtCompanyId", mCompanyInfo.getCompany_id(), Field.TYPE_INT);
        params.put("txtFloor", txtFloor, Field.TYPE_STRING);
        params.put("txtUnder", txtUnder, Field.TYPE_STRING);
        params.put("txtCompanyCode", mCompanyInfo.getCompany_code(), Field.TYPE_STRING);
        params.put("chkOccupy", radioAll.isChecked() ? "1" : "0", Field.TYPE_INT);
        params.put("txtEast", StringUtils.nullValue(metEast.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtSouth", StringUtils.nullValue(metSouth.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtWest", StringUtils.nullValue(metWest.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtNorth", StringUtils.nullValue(metNorth.getText().toString().trim()), Field.TYPE_STRING);

        getSinglePhotoUploadItem(this.mPhotoInfo, new SelectEvidenceAdapter.CropCallBack<String>() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mHUDUtil.showHUD();
                    }
                });
            }

            @Override
            public void onFinish(String data) {
                if (StringUtils.nullValue(data).length() != 0) {
                    params.put("file_url", data);
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        SafeDataServices.init().saveBuildingInfoAction(params, isEdit);
                    }
                });
            }
        });
    }


    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_SAVE == event.getTag()) {//建筑保存
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            BuildingRefreshEvent refreshEvent = new BuildingRefreshEvent();
                            refreshEvent.setTag(EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_REFRESH);
                            AppService.getBus().post(refreshEvent);
                            AppManager.getAppManager().finishActivity(SafeDataCollectionBuildingPropActivity.this);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompanyBuildingVo = null;
        mCompanyInfo = null;
        IApplication._tempBuildPropActivity = null;
        System.gc();

    }
}
